local japi = require 'jass.japi'
local jass = require 'jass.common'

local move = {}

function move.add(u)
	local handle = u.handle
	move.last[handle] = u:get_point()
	table.insert(move.group, u)
end

function move.remove(u)
	local handle = u.handle
	if move.last[handle] then 
		move.last[handle] = nil
		for i, uu in ipairs(move.group) do
			if u == uu then
				table.remove(move.group, i)
				break
			end
		end
	end
end

		
function ac.unit.__index:update_speed()
	local speed = self:get('移动速度') * (self:get '移速增幅'+100) * 0.01
	local handle = self.handle
	if speed > 522 and not move.last[handle] then
		move.add(self)
	elseif speed <= 522 and move.last[handle] then
		move.remove(self)
	end
end

function move.init()
	move.last = {}
	move.group = {}
	ac.game:on '单位-即将移除' (function(_,u)
		move.remove(u)
	end)
end

function move.update(frame)
	for _, u in ipairs(move.group) do
		local handle = u.handle
		local last = move.last[handle]
		local now = u:get_point()
		local speed = now * last / frame
        local max = math.min( u:get('移动速度') * (u:get '移速增幅'+100) * 0.01, 768) 
		if speed > 520 and speed < 525 then
			--认为是正常移动
			local target = last - {last / now, max * frame}
			u:set_point(target)
			move.last[handle] = target
		else
			move.last[handle] = now
		end
	end
end

return move
